<template>
  <div class="roles-container">
    <div class="page-header">
      <h2 class="page-title">角色权限管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="showRoleDialog('add')">
          <el-icon><Plus /></el-icon>
          新增角色
        </el-button>
      </div>
    </div>

    <div class="roles-content">
      <!-- 左侧角色列表 -->
      <div class="roles-list">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>角色列表</span>
            </div>
          </template>
          <div class="role-items">
            <div 
              v-for="role in roles" 
              :key="role.id" 
              class="role-item"
              :class="{ active: currentRole && currentRole.id === role.id }"
              @click="selectRole(role)"
            >
              <div class="role-info">
                <el-tag :type="getRoleTagType(role.code)" effect="dark">{{ role.name }}</el-tag>
                <div class="role-desc">{{ role.description }}</div>
              </div>
              <div class="role-actions">
                <el-button 
                  type="primary" 
                  text 
                  size="small" 
                  @click.stop="showRoleDialog('edit', role)"
                >
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button 
                  type="danger" 
                  text 
                  size="small" 
                  @click.stop="handleDelete(role)"
                  :disabled="role.isSystem"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 右侧权限详情 -->
      <div class="permissions-content">
        <el-card shadow="hover" v-if="currentRole">
          <template #header>
            <div class="card-header">
              <div>
                <span>角色权限设置</span>
                <el-tag :type="getRoleTagType(currentRole.code)" class="ml-2">{{ currentRole.name }}</el-tag>
              </div>
              <el-button type="primary" size="small" @click="savePermissions">保存权限</el-button>
            </div>
          </template>
          
          <div class="permissions-tree">
            <div class="tree-header">
              <el-checkbox 
                v-model="checkAll" 
                :indeterminate="isIndeterminate"
                @change="handleCheckAllChange"
              >
                全选/全不选
              </el-checkbox>
              <div class="expand-actions">
                <el-button type="text" @click="expandAll">展开全部</el-button>
                <el-divider direction="vertical" />
                <el-button type="text" @click="collapseAll">折叠全部</el-button>
              </div>
            </div>
            
            <el-tree
              ref="permissionTreeRef"
              :data="permissionsTree"
              :props="defaultProps"
              show-checkbox
              node-key="id"
              :default-checked-keys="currentRole ? currentRole.permissions : []"
              @check="handleCheckChange"
            />
          </div>
        </el-card>
        
        <div class="no-role-selected" v-else>
          <el-empty description="请选择左侧角色以设置权限" />
        </div>
      </div>
    </div>

    <!-- 角色表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增角色' : '编辑角色'"
      width="500px"
    >
      <el-form :model="roleForm" label-width="100px" ref="roleFormRef" :rules="roleRules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色标识" prop="code">
          <el-input v-model="roleForm.code" placeholder="请输入角色标识" :disabled="dialogType === 'edit' && roleForm.isSystem" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input 
            v-model="roleForm.description" 
            type="textarea" 
            rows="3" 
            placeholder="请输入角色描述" 
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="roleForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRoleForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="删除角色"
      width="400px"
    >
      <div class="delete-confirm">
        <el-icon class="warning-icon"><WarningFilled /></el-icon>
        <p>确定要删除角色 <strong>{{ roleToDelete?.name }}</strong> 吗？</p>
        <p class="warning-text">删除后将无法恢复，该角色下的用户将无法正常使用系统！</p>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确认删除</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { 
  Plus,
  Edit,
  Delete,
  WarningFilled
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 角色和权限相关
const roles = ref([])
const currentRole = ref(null)
const permissionTreeRef = ref(null)
const checkAll = ref(false)
const isIndeterminate = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const roleFormRef = ref(null)
const deleteDialogVisible = ref(false)
const roleToDelete = ref(null)

// 角色表单验证规则
const roleRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色标识', trigger: 'blur' },
    { pattern: /^[a-zA-Z_]+$/, message: '角色标识只能包含字母和下划线', trigger: 'blur' }
  ]
}

// 角色表单
const roleForm = ref({
  id: '',
  name: '',
  code: '',
  description: '',
  status: 1,
  isSystem: false,
  permissions: []
})

// 权限树属性
const defaultProps = {
  children: 'children',
  label: 'label'
}

// 初始化角色数据
const initRolesData = () => {
  roles.value = [
    {
      id: 1,
      name: '管理员',
      code: 'admin',
      description: '系统管理员，拥有所有权限',
      status: 1,
      isSystem: true,
      permissions: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
    },
    {
      id: 2,
      name: '项目经理',
      code: 'manager',
      description: '负责项目的全面管理和监督',
      status: 1,
      isSystem: true,
      permissions: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
    },
    {
      id: 3,
      name: '施工负责人',
      code: 'worker',
      description: '负责现场施工和任务执行',
      status: 1,
      isSystem: true,
      permissions: [1, 2, 5, 6, 7]
    }
  ]
}

// 权限树数据
const permissionsTree = [
  {
    id: 1,
    label: '仪表盘',
    children: [
      {
        id: 2,
        label: '查看数据概览'
      }
    ]
  },
  {
    id: 3,
    label: '项目管理',
    children: [
      {
        id: 4,
        label: '查看项目列表'
      },
      {
        id: 5,
        label: '新增项目'
      },
      {
        id: 6,
        label: '编辑项目'
      },
      {
        id: 7,
        label: '删除项目'
      }
    ]
  },
  {
    id: 8,
    label: '任务管理',
    children: [
      {
        id: 9,
        label: '查看任务'
      },
      {
        id: 10,
        label: '创建任务'
      },
      {
        id: 11,
        label: '编辑任务'
      },
      {
        id: 12,
        label: '删除任务'
      }
    ]
  },
  {
    id: 13,
    label: '进度管理',
    children: [
      {
        id: 14,
        label: '查看甘特图'
      },
      {
        id: 15,
        label: '进度跟踪'
      }
    ]
  },
  {
    id: 16,
    label: '系统管理',
    children: [
      {
        id: 17,
        label: '用户管理'
      },
      {
        id: 18,
        label: '角色管理'
      },
      {
        id: 19,
        label: '数据统计'
      },
      {
        id: 20,
        label: '系统设置'
      }
    ]
  }
]

// 选择角色
const selectRole = (role) => {
  currentRole.value = role
  
  // 设置权限树选中状态
  nextTick(() => {
    if (permissionTreeRef.value) {
      permissionTreeRef.value.setCheckedKeys(role.permissions)
      updateCheckAllStatus()
    }
  })
}

// 获取角色标签类型
const getRoleTagType = (code) => {
  const types = {
    'admin': 'danger',
    'manager': 'warning',
    'worker': 'info'
  }
  return types[code] || 'success'
}

// 显示角色对话框
const showRoleDialog = (type, role = null) => {
  dialogType.value = type
  
  // 重置表单
  if (roleFormRef.value) {
    roleFormRef.value.resetFields()
  }
  
  if (type === 'add') {
    roleForm.value = {
      id: '',
      name: '',
      code: '',
      description: '',
      status: 1,
      isSystem: false,
      permissions: []
    }
  } else if (type === 'edit' && role) {
    roleForm.value = { ...role }
  }
  
  dialogVisible.value = true
}

// 提交角色表单
const submitRoleForm = () => {
  roleFormRef.value.validate((valid) => {
    if (!valid) return
    
    if (dialogType.value === 'add') {
      // 添加角色
      const newRole = {
        ...roleForm.value,
        id: Date.now(),
        permissions: []
      }
      roles.value.push(newRole)
      ElMessage.success('角色添加成功')
    } else {
      // 更新角色
      const index = roles.value.findIndex(r => r.id === roleForm.value.id)
      if (index !== -1) {
        roles.value[index] = { ...roles.value[index], ...roleForm.value }
        
        // 如果当前正在编辑选中的角色，更新currentRole
        if (currentRole.value && currentRole.value.id === roleForm.value.id) {
          currentRole.value = { ...roles.value[index] }
        }
        
        ElMessage.success('角色更新成功')
      }
    }
    
    dialogVisible.value = false
  })
}

// 删除角色
const handleDelete = (role) => {
  if (role.isSystem) {
    ElMessage.warning('系统内置角色不能删除')
    return
  }
  
  roleToDelete.value = role
  deleteDialogVisible.value = true
}

// 确认删除
const confirmDelete = () => {
  if (!roleToDelete.value) return
  
  const index = roles.value.findIndex(r => r.id === roleToDelete.value.id)
  if (index !== -1) {
    roles.value.splice(index, 1)
    
    // 如果删除的是当前选中的角色，清空当前选中
    if (currentRole.value && currentRole.value.id === roleToDelete.value.id) {
      currentRole.value = null
    }
    
    ElMessage.success('角色删除成功')
    deleteDialogVisible.value = false
  }
}

// 保存权限设置
const savePermissions = () => {
  if (!currentRole.value) return
  
  const checkedKeys = permissionTreeRef.value.getCheckedKeys()
  const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys()
  const allCheckedKeys = [...checkedKeys, ...halfCheckedKeys]
  
  // 更新当前角色的权限
  const index = roles.value.findIndex(r => r.id === currentRole.value.id)
  if (index !== -1) {
    roles.value[index].permissions = allCheckedKeys
    currentRole.value.permissions = allCheckedKeys
    ElMessage.success('权限保存成功')
  }
}

// 权限选择变化
const handleCheckChange = () => {
  updateCheckAllStatus()
}

// 更新全选状态
const updateCheckAllStatus = () => {
  const checkedCount = permissionTreeRef.value.getCheckedKeys().length
  const total = getAllPermissionIds().length
  
  checkAll.value = checkedCount === total
  isIndeterminate.value = checkedCount > 0 && checkedCount < total
}

// 获取所有权限ID
const getAllPermissionIds = () => {
  const ids = []
  
  const traverse = (nodes) => {
    nodes.forEach(node => {
      ids.push(node.id)
      if (node.children && node.children.length) {
        traverse(node.children)
      }
    })
  }
  
  traverse(permissionsTree)
  return ids
}

// 全选/全不选
const handleCheckAllChange = (val) => {
  const allPermissionIds = getAllPermissionIds()
  permissionTreeRef.value.setCheckedKeys(val ? allPermissionIds : [])
  isIndeterminate.value = false
}

// 展开全部节点
const expandAll = () => {
  expandOrCollapseNodes(true)
}

// 折叠全部节点
const collapseAll = () => {
  expandOrCollapseNodes(false)
}

// 展开或折叠所有节点
const expandOrCollapseNodes = (expand) => {
  const allNodes = permissionTreeRef.value.store._getAllNodes()
  allNodes.forEach(node => {
    node.expanded = expand
  })
}

// 初始化
onMounted(() => {
  initRolesData()
})
</script>

<style lang="scss" scoped>
.roles-container {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    .page-title {
      margin: 0;
      font-size: 24px;
      font-weight: 600;
      color: #303133;
    }
  }
  
  .roles-content {
    display: flex;
    gap: 20px;
    
    .roles-list {
      width: 300px;
      flex-shrink: 0;
      
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-weight: bold;
      }
      
      .role-items {
        max-height: 600px;
        overflow-y: auto;
        
        .role-item {
          padding: 12px;
          border-radius: 4px;
          cursor: pointer;
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 8px;
          transition: all 0.3s;
          
          &:hover {
            background-color: #f5f7fa;
          }
          
          &.active {
            background-color: #ecf5ff;
          }
          
          .role-info {
            .role-desc {
              color: #909399;
              font-size: 12px;
              margin-top: 8px;
            }
          }
          
          .role-actions {
            opacity: 0;
            transition: opacity 0.3s;
          }
          
          &:hover .role-actions {
            opacity: 1;
          }
        }
      }
    }
    
    .permissions-content {
      flex: 1;
      
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .ml-2 {
          margin-left: 8px;
        }
      }
      
      .permissions-tree {
        margin-top: 16px;
        
        .tree-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;
          
          .expand-actions {
            display: flex;
            align-items: center;
            
            .el-divider {
              height: 16px;
              margin: 0 8px;
            }
          }
        }
      }
      
      .no-role-selected {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 400px;
        background-color: #f5f7fa;
        border-radius: 4px;
      }
    }
  }
  
  .delete-confirm {
    text-align: center;
    padding: 20px 0;
    
    .warning-icon {
      font-size: 48px;
      color: #E6A23C;
      margin-bottom: 16px;
    }
    
    p {
      margin: 8px 0;
      font-size: 16px;
    }
    
    .warning-text {
      color: #F56C6C;
      font-weight: bold;
    }
  }
}
</style> 